const MAX_WORDS = 140; //文字最大数
const MAX_IMG_NUM = 9; //图片数量
const db = wx.cloud.database();
let content = '' //文字内容
let userInfo = {} //用户头像，昵称
Page({

  /**
   * 页面的初始数据
   */
  data: {
    wordsNum: 0, //输入文字个数,
    footerBottom: 0, //顶部位置
    images: [],
    content: '',
    touchStartTime: 0,
    touchEndTime: 0,
    lastTapTime: 0,
    lastTapTimeoutFunc: function() {},
    selectPhone: true // 添加图片的按钮是否显示
  },
  onLoad: function(options) {
    console.log(options)
    userInfo = options
  },
  onInput(event) {
    // console.log(event)
    this.setData({
      content: event.detail.value
    })
    this.wordsNumFn()
  },
  //刷新剩余文字个数
  wordsNumFn() {
    let wordsNum = this.data.content.length;
    if (wordsNum >= MAX_WORDS) {
      wordsNum = `最大字数为${MAX_WORDS}`
    }
    this.setData({
      wordsNum: wordsNum
    })
  },
  //获取焦点
  onFocus(event) {
    //模拟器获取键盘高度
    this.setData({
      footerBottom: event.detail.height + 'px'
    })
    console.log(this.data.footerBottom)
  },
  //失去焦点
  onBlur(event) {
    this.setData({
      footerBottom: 0
    })
  },
  //选择图片
  selectImages() {
    //还能再选几张
    let max = MAX_IMG_NUM - this.data.images.length;
    wx.chooseImage({
      count: max,
      sizeType: ["original", "compressed"], // 大小
      sourceType: ["album", "camera"], //来源
      success: (res) => {
        // console.log(res)
        this.setData({
          images: this.data.images.concat(res.tempFilePaths)
        })
        //还能上传几张
        max = MAX_IMG_NUM - this.data.images.length;
        this.setData({
          selectPhone: max <= 0 ? false : true
        })

      },
    })
  },
  //删除图片
  onDelImg(event) {
    const index = event.target.dataset.index
    this.data.images.splice(index, 1)
    this.setData({
      images: this.data.images
    })
    if (this.data.images.length === MAX_IMG_NUM - 1) {
      this.setData({
        selectPhone: true
      })
    }
  },
  //查看图片
  previewImage(event) {
    wx.previewImage({
      urls: this.data.images,
      current: event.target.dataset.src
    })
  },
  //发布
  send() {
    /**
     * 数据 ===》 云数据库
     * 数据库：内容。图片fileID，openID，昵称，头像，时间
     */
    content = this.data.content;
    if (content.trim() === "") {
      wx.showModal({
        title: '请输入内容',
        content: '',
      })
      return false;
    }
    wx.showModal({
      title: '提示',
      content: '是否确认发布？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: "发布中",
            mask: true
          })

          let promiseArr = [];
          let fileIds = [];
          //图片上传 -- 小程序只能一张一张上传
          for (let i = 0, len = this.data.images.length; i < len; i++) {
            let p = new Promise((resolve, reject) => {
              //文件扩展名
              let item = this.data.images[i]
              let suffix = /\.\w+$/.exec(item)[0]
              wx.cloud.uploadFile({
                cloudPath: 'blog/' + Date.now() + '-' + Math.random() * 10000000 + suffix,
                filePath: item,
                success: (res) => {
                  fileIds = fileIds.concat(res.fileID)
                  console.log(res.fileID)
                  resolve()

                },
                fail: (err) => {
                  console.error(err)
                  reject()
                }
              })
            })
            promiseArr.push(p)
          }
          //存入云数据库
          Promise.all(promiseArr).then(res => {
            db.collection('blog').add({
              data: {
                avatarUrl: userInfo.avatarUrl,
                nickName: userInfo.nickName,
                content,
                img: fileIds,
                createTime: db.serverDate(), //服务端时间
              }
            }).then(res => {
              wx.hideLoading()
              wx.showToast({
                title: '发布成功',
              })
              //返回博客,并且刷新
              wx.navigateBack()
              //刷新
              const pages = getCurrentPages();
              console.log(pages)
              const prevPage = pages[pages.length - 2];
              prevPage.onPullDownRefresh()
            })
          }).catch(err => {
            wx.hideLoading();
            wx.showToast({
              title: '发布失败',
            })
          })
        }else{
          return false;
        }
      }
    })

  },
  touchStart(e) {
    this.data.touchEndTime = e.timeStamp;
  },
  touchEnd(e) {
    this.data.touchEndTime = e.timeStamp;
  },
  multipleTap(e) {
    if (this.data.touchStartTime - this.data.touchEndTime < 350) {
      let currentTime = e.timeStamp;
      let lastTapTime = this.data.lastTapTime;
      this.data.lastTapTime = currentTime;
      if (currentTime - lastTapTime < 300) {
        this.getsayLove();
      } else {
        this.data.lastTapTimeoutFunc = setTimeout(function() {
          console.log("tap")
        }, 300);
      }
    }
  },
  //长按
  pressTap() {
    let that = this;
    let touchTime = that.data.touchEnd - that.data.touchStart;
    if (touchTime > 3000) {
      console.log(1)
    } else {
      return false
    }
  },
  longTap() {
    this.getsayLove()
  },
  getsayLove() {
    wx.showLoading({
      title: '加载中...',
    })
    wx.cloud.callFunction({
      name: 'blog',
      data: {
        $url: 'saylove'
      }
    }).then(res => {
      content = res.result.content;
      this.setData({
        content
      })
      this.wordsNumFn()
      wx.hideLoading();
    })
  }
})